//
//  UserInfoViewController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/21.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UserInfoCell.h"
#import "UserNameController.h"
#import "UserAgeController.h"
#import "UserAddressController.h"
#import "UserAreaController.h"
#import "DetailViewController.h"
#import "FloaterAlertView.h"
#import "UpLoadImageManager.h"


@interface UserInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) UIImage *userImage;
@property (nonatomic, copy) NSString *sexStr;
@property (nonatomic, copy) NSString *nameStr;
@property (nonatomic, copy) NSString *mobileStr;
@property (nonatomic, copy) NSString *photoStr;
@property (nonatomic, copy) NSString *addressStr;
@property (nonatomic, copy) NSString *areaStr;
@property (nonatomic, copy) NSString *ageStr;
@end

@implementation UserInfoViewController

- (NSArray *)titleArray
{
    if (!_titleArray) {
        self.titleArray = [[NSArray alloc]initWithObjects:@[@"头像",@"性名",@"姓别",@"年龄"],@[@"地区",@"家庭住址"], nil];
    }
    return _titleArray;
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sexAction:) name:@"sex" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nameAction:) name:@"name" object:nil];

    NSString *userNameKey = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserNameKey];
    NSString *userPhotoUrl = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserPhotoUrl];
    NSString *userSex = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultKey_Sex];
    NSString *userArea = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultArea];
    NSString *userAge = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultAge];
    NSString *userAddress = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultAddress];
    self.nameStr = userNameKey;
    self.sexStr = userSex;
    self.photoStr = userPhotoUrl;
    self.areaStr = userArea;
    self.ageStr = userAge;
    self.addressStr = userAddress;
    if (userPhotoUrl == nil || userNameKey == nil || userSex == nil || userArea == nil || userAge == nil || userAddress == nil) {
        [self webRequest_GetUserInfoMessage];
    }
    [self.tableView reloadData];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sex" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"name" object:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"个人信息";
    __weak typeof(self)weakSelf = self;
    [self addLeftButtonWithImage:[UIImage imageNamed:@"返回箭头"] actionBlock:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"UserInfoCell" bundle:nil] forCellReuseIdentifier:@"UserInfoCell"];
    
}

#pragma mark - webRequest
-(void)webRequest_GetUserInfoMessage
{
    NSString *uidStr = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsUserIdKey];
    NSDictionary *dict = @{@"uid":uidStr};
    [HttpRequestManager getMethod:KUserInfoInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        
        if (success) {
            self.photoStr = response[@"data"][@"headimgurl"];
            self.mobileStr = response[@"data"][@"mobile"];
            self.nameStr = response[@"data"][@"nickname"];
            self.sexStr = response[@"data"][@"sex"];
            self.areaStr = response[@"data"][@"city"];
            self.addressStr = response[@"data"][@"address"];
            self.ageStr = response[@"data"][@"age"];
            if ([response[@"data"][@"nickname"] isEqualToString:response[@"data"][@"mobile"]]) {
                self.nameStr = @"请填写真实名字";
            }
            [self.tableView reloadData];
        }else{
            
        }
    }];
}

- (void)sexAction:(NSNotification *)sender
{
    self.sexStr = sender.object;
    
    [self.tableView reloadData];
}

- (void)nameAction:(NSNotification *)name
{
    self.nameStr = name.object;
    
    [self.tableView reloadData];
}

- (void)configureSexView
{
    FloaterAlertView *test = [FloaterAlertView instanceTextView];
    
    [test configWithLayers];
    test.cancelBlock = ^(){
        //            DLog(@"456");
    };
    [test setCenter:CGPointMake(AppBounds.size.width/2, AppBounds.size.height/2)];
    [test show];
}


#pragma mark ---tableViewDelegate---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.titleArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoCell" forIndexPath:indexPath];
    
    cell.titleLabel.text = self.titleArray[indexPath.section][indexPath.row];
 
    if (indexPath.section == 0) {
        if (indexPath.row == 0) { // 头像
            cell.detailLabel.hidden = YES;
            if (self.photoStr != nil) {
                [cell.userImage sd_setImageWithURL:[NSURL URLWithString:self.photoStr] placeholderImage:[UIImage imageNamed:@"个人头像"]];
            }
        }else if(indexPath.row == 1){ // 姓名
            cell.userImage.hidden = YES;
            cell.detailLabel.text = self.nameStr;
            
        }else if(indexPath.row == 2){ // 性别
            cell.userImage.hidden = YES;
            cell.detailLabel.text = self.sexStr;
            
        }else if(indexPath.row == 3){ // 年龄
            cell.userImage.hidden = YES;
            
            cell.detailLabel.text = self.ageStr;
            
        }
    }else {
        cell.userImage.hidden = YES;
        if(indexPath.row == 0){ // 地区
            cell.detailLabel.text = self.areaStr;
            
        }else if(indexPath.row == 1){ // 住址
            cell.detailLabel.text = self.addressStr;
            
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 20;
    } else {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView reloadData];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) { // 头像
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片"
                                                              delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
            
            [sheet showInView:self.view.window];
            
        } else if (indexPath.row == 1) {// 姓名
            UserNameController *nameVC = [[UserNameController alloc]init];
            [self.navigationController pushViewController:nameVC animated:YES];
            
        } else if (indexPath.row == 2) { // 性别
            [self configureSexView];
            
        } else if (indexPath.row == 3) { // 年龄
            UserAgeController *ageVC = [[UserAgeController alloc]init];
            [self.navigationController pushViewController:ageVC animated:YES];
        }
        
    }else {
        if (indexPath.row == 0) { // 地区
            UserAreaController *arerVC = [[UserAreaController alloc]init];
            [self.navigationController pushViewController:arerVC animated:YES];
            
        } else if (indexPath.row == 1){ // 家庭住址
            UserAddressController *addressVC = [[UserAddressController alloc]init];
            [self.navigationController pushViewController:addressVC animated:YES];
        }
    }
    
}

//返回cell的高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 70;
        }else {
            return 50;
        }
    }else {
        return 50;
    }
}

#pragma mark ---UIActionSheetDelegate---
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == [actionSheet cancelButtonIndex]) {
        return;
    }
    UIImagePickerController *pic = [[UIImagePickerController alloc]init];
    switch (buttonIndex) {
        case 0:{ //拍照
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                return;
            }
            //设置图片来源
            pic.sourceType = UIImagePickerControllerSourceTypeCamera;
            //设置代理
            pic.delegate = self;
            break;
        }
        case 1: {
            //相册
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                return;
            }
            //设置图片来源
            pic.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //设置代理
            pic.delegate = self;
            break;
        }
        default:
            break;
    }
    //显示控制器
    [self presentViewController:pic animated:YES completion:nil];
}

#pragma mark --UIImagePickerControllerDelegate--
/**
 *  在选择完图片后调用
 *  @param info   里面包含了图片信息
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
        [picker dismissViewControllerAnimated:YES completion:^{
        [UpLoadImageManager uploadImage:image uploadImageURL:KUpLoadPicInterface withCompltedBlock:^(BOOL success, NSString *urlString) {
            if (success) {
                self.photoStr = urlString;
                [[NSUserDefaults standardUserDefaults] setObject:urlString forKey:KUserDefaultsUserPhotoUrl];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self.tableView reloadData];
            }else{
                NSLog(@"%@",urlString);
            }
        }];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
